package com.zengqingfa.thread.demo6;

/**
 * @fileName: DeadLock
 * @author: zengqf3
 * @date: 2020-10-7 19:55
 * @description:
 */
//死锁 多个线程互相持有对方需要的资源，然后形成僵持
public class DeadLock2 {

    public static Object obj1 = new Object();
    public static Object obj2 = new Object();

    public static void main(String[] args) {
        new Thread(new Lock(false)).start();
        new Thread(new Lock(true)).start();
    }

}

class Lock implements Runnable {

    private boolean flag;

    public Lock(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag) {
            synchronized (DeadLock2.obj1) {
                System.out.println("获得obj1的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (DeadLock2.obj2) {
                    System.out.println("获得obj2的锁");
                }
            }
        } else {
            synchronized (DeadLock2.obj2) {
                System.out.println("获得obj2的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (DeadLock2.obj1) {
                    System.out.println("获得obj1的锁");
                }
            }
        }
    }
}


